import { jwtDecode } from "jwt-decode";


const Utils = (function () {

    let commonInstance;

    function init() {
        function log(message) {
            console.log(message);
        }
        return { log };
    }

    return {

        getCommonInstance: function () {
            if (!commonInstance) {
                commonInstance = init();
            }

            return commonInstance;
        },
    }

})()


export const uniqueId = () => {
    return 'id-' + window.performance.now().toString().replace('.', '') + Math.random().toString(36).substr(2, 9);
}


export const getCookie = function (cookieName) {
    const strCookie = document.cookie
    const cookieList = strCookie.split(';')

    for (let i = 0; i < cookieList.length; i++) {
        const arr = cookieList[i].split('=')
        if (cookieName === arr[0].trim()) {
            return arr[1]
        }
    }

    return ''
}



export const isAdmin = function () {
    let isAdmin = false

    let access_token = localStorage.getItem("access_token")
    let user_info = jwtDecode(access_token)
    // console.log(user_info)

    try {
        if (user_info && user_info['sub']) {
            let sub = JSON.parse(user_info['sub'])

            if (sub && sub['user_name'] === "root" && sub['role'] === 0) {
                isAdmin = true
            }
        }

        return isAdmin
    } catch (e) {
        return false
    }
}



//清除所有cookie函数
function clearAllCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g)

    if(keys) {
        for(var i = keys.length; i--;)
        document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
}



export const logoutAction = () => {
    localStorage.removeItem('access_token')
    // document.cookie = ''
    clearAllCookie()

    window.location.href = `${window.location.origin}${window.location.pathname}#/login`
}

